package com.roc.web.action.profit;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.dao.DaoException;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitDetail;
import com.roc.service.IExcelExportService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.service.profit.IProfitService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/profit")
public class ProfitDASumQueryAction  extends PaginationBaseAction{

	private Logger logger=LogManager.getLogger(ProfitDASumQueryAction.class);
	private ProfitDASumQuerySearchCondition searchCondition;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IPowerInfoService powerInfoService;
	@Autowired
	private IProfitService profitService;
	@Autowired
	private IExcelExportService excelExportService;
	
	private InputStream excelFile;

	private String excelName;
	
	@Action(value = "initProfitDirectlyAgentSum", results = {@Result(name = "success", location = "/pages/profit/profitDirectlyAgentSum.jsp") })
	public String initProfitDirectlyAgentSum() throws ServiceException{
		init();
		return SUCCESS;
	}
	
	
	private void init()throws ServiceException{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map map= new HashMap();
		try{
			//根据登录人角色显示不同代理商
			Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
			//String orgCode=mapReal.get("orgCode");
            String superRole= mapReal.get("superRole");
            String opRealId =mapReal.get("opRealId");
            //销售
            if(Role.MARKET_DIRECT.getCode().equals(superRole)||Role.MARKET_LEAD.getCode().equals(superRole)){
				 map =  profitService.getDirectlyAgentIdsTreeByRealId(Long.parseLong(opRealId));
			}//其他
			else{
				 map =  profitService.getDirectlyAgentIdsTreeBySuperId(Long.parseLong(opRealId));
			}
			getRequest().setAttribute("agnetList",map);
		}
		catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
	}
	
	@Action(value = "queryProfitDASum", results = { 
			@Result(name = "success", location = "/pages/profit/profitDirectlyAgentSum.jsp"),
            @Result(name="error",location="/pages/profit/profitDirectlyAgentSum.jsp"),
            @Result(name="login",location="/pages/profit/profitDirectlyAgentSum.jsp") })

	public String search() throws ServiceException, DaoException{
		init();
		if(searchCondition==null){
			searchCondition=(ProfitDASumQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new ProfitDASumQuerySearchCondition();
			}
		}
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				if(-1==searchCondition.getId()){
					logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
					Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
		            String superRole= mapReal.get("superRole");
		            String opRealId =mapReal.get("opRealId");
					//long id=1;
					String ids = null;
					//销售
					if(Role.MARKET_DIRECT.getCode().equals(superRole)||Role.MARKET_LEAD.getCode().equals(superRole)){
					 ids =  profitService.getOpertorsScIdById(Long.parseLong(opRealId));
					}//管理员
					else{
					 ids =  profitService.getDirectlyAgentIdsBySuperId(Long.parseLong(opRealId));
					}
					searchCondition.setIds(ids);
				}
			
			//this.setCurrentPage(this.checkCurrentPage());
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			//searchRsList=pagenitionService.findAllSQL(searchCondition, 0, 9999999);
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			//this.setTotalPage(this.calcuTotalPage(1));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("totalType",searchCondition.getTotalType());
			setSearchToConditionSession(searchCondition);
		
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError("分润汇总查询失败");
			
		}
		return SUCCESS;
	}
	
	@Action(value="exportProfitDASum",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=\"${excelName}\"",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/profit/profitDirectlyAgentSum.jsp") }) 
	public String  exportProfitDASum() throws Exception{
		
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				
				if(searchCondition==null){
					searchCondition=(ProfitDASumQuerySearchCondition)getSearchConditionFromSession();
					if(searchCondition==null){
						searchCondition=new ProfitDASumQuerySearchCondition();
					}
				}
				String temp =searchCondition.getBeginTime()+"至"+searchCondition.getEndTime()+"直属分润汇总查询.xls";	
				if(-1!=searchCondition.getId()){
					Operators operators=profitService.loadById(searchCondition.getId());
					if(null !=operators){
						temp = operators.getRealName()+"--"+searchCondition.getBeginTime()+"至"+searchCondition.getEndTime()+"直属分润汇总查询的分润.xls";	
					}
				}else{
					Map<String, String> mapReal=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(),logingOperators.getRoleType(),logingOperators.getId(),logingOperators.getOrgCode());
		            String superRole= mapReal.get("superRole");
		            String opRealId =mapReal.get("opRealId");
		            String ids;
					//销售
					if(Role.MARKET_DIRECT.getCode().equals(superRole)||Role.MARKET_LEAD.getCode().equals(superRole)){
					 ids =  profitService.getOpertorsScIdById(Long.parseLong(opRealId));
					}//管理员
					else{
					ids =  profitService.getDirectlyAgentIdsBySuperId(Long.parseLong(opRealId));
					}
					searchCondition.setIds(ids);
				}
				excelName=new String(temp.getBytes(),"ISO8859-1");
				try {
					searchRsList=pagenitionService.findAllSQL(searchCondition,  0, 9999999);
					dealWithTheList(searchRsList);
					String  reportName = "直属分润汇总查询";//标题名字
					String[]  headArray; //表格列头
					if(1==searchCondition.getTotalType()){
						headArray=new String[]{"代理商名称","交易类型","总笔数","总金额","实际分润","结算时间"};
					}else if(2==searchCondition.getTotalType()){
						headArray=new String[]{"代理商名称","卡类型","总笔数","总金额","实际分润","结算时间"};
					}else{
						headArray=new String[]{"代理商名称","卡类型","交易类型","总笔数","总金额","实际分润","结算时间"};
					}
					
					HSSFWorkbook work=excelExportService.excelExport(reportName, headArray, searchRsList);

					 ByteArrayOutputStream output = new ByteArrayOutputStream();  
					         work.write(output);  
					   
					        byte[] ba = output.toByteArray();  
					         excelFile = new ByteArrayInputStream(ba);  
					         output.flush();  
					         output.close();  
					
		}catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	
	private void dealWithTheList(List<Object> list) {
		// TODO Auto-generated method stub
		List<Object> tempList=new ArrayList<Object>();
		try {
			if(list!=null&&list.size()>0){
				Map<String,BigDecimal> map = this.getProfitPercent(list);
				for (int i=0;i<list.size();i++){
					
					Object[] obj=(Object[]) list.get(i);
					Object[] prof=new Object[obj.length];
					String accountNo ="";
					if(1==searchCondition.getTotalType()){
						accountNo =Constance.Null2EmptyTrim(obj[6]);
					}else if(2==searchCondition.getTotalType()){
						accountNo =Constance.Null2EmptyTrim(obj[6]);
					}else{
						accountNo =Constance.Null2EmptyTrim(obj[7]);
					}
					BigDecimal merfee =new BigDecimal(Constance.null2Amt(obj[2]));
					BigDecimal percent = map.get(accountNo);
					BigDecimal realMerfee=merfee.multiply(percent);
				
					
					prof[0]=(Constance.Null2EmptyTrim(obj[0]));
					if(1==searchCondition.getTotalType()){
						prof[1]=Constance.Null2EmptyTrim(obj[5]);
						prof[2]=(Constance.Null2EmptyTrim(obj[3]));
						prof[3]=new BigDecimal(Constance.null2Amt(obj[1]));
						prof[4]=realMerfee;
						prof[5]=(Constance.Null2EmptyTrim(obj[4]));
					}else if(2==searchCondition.getTotalType()){
						prof[1]=Constance.Null2EmptyTrim(obj[5]);
						prof[2]=(Constance.Null2EmptyTrim(obj[3]));
						prof[3]=new BigDecimal(Constance.null2Amt(obj[1]));
						prof[4]=realMerfee; 
						prof[5]=(Constance.Null2EmptyTrim(obj[4]));
					}else{
					
						prof[1]=Constance.Null2EmptyTrim(obj[5]);
						prof[2]=Constance.Null2EmptyTrim(obj[6]);
						prof[3]=(Constance.Null2EmptyTrim(obj[3]));    
						prof[4]=new BigDecimal(Constance.null2Amt(obj[1]));
						prof[5]=realMerfee;
						prof[6]=(Constance.Null2EmptyTrim(obj[4]));
					}
							
				tempList.add(prof);
						
				}
			}
				
				searchRsList=tempList;
			
		} catch (Exception e) {
			logger.error("数据处理异常"+e.getMessage(),e);
		}
		
	}
	
	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		// TODO Auto-generated method stub
	List<ProfitDetail> tempList=new ArrayList<ProfitDetail>();
	try {
		if(list!=null&&list.size()>0){
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				ProfitDetail prof=new ProfitDetail();
					Object[] obj=(Object[]) iterator.next();
				
				
					prof.setAgentName(Constance.Null2EmptyTrim(obj[0]));
					prof.setSAmt(new BigDecimal(Constance.null2Amt(obj[1])));
					prof.setMerfee(new BigDecimal(Constance.null2Amt(obj[2])));
					prof.setTCount(Constance.Null2EmptyTrim(obj[3]));
					prof.setCreateDate(Constance.Null2EmptyTrim(obj[4]));
					if(1==searchCondition.getTotalType()){
						prof.setProdCd(Constance.Null2EmptyTrim(obj[5]));
						prof.setAccountNo(Constance.Null2EmptyTrim(obj[6]));
					}else if(2==searchCondition.getTotalType()){
						prof.setCardClass(Constance.Null2EmptyTrim(obj[5]));
						prof.setAccountNo(Constance.Null2EmptyTrim(obj[6]));
					}else{
						prof.setProdCd(Constance.Null2EmptyTrim(obj[5]));
						prof.setCardClass(Constance.Null2EmptyTrim(obj[6]));
						prof.setAccountNo(Constance.Null2EmptyTrim(obj[7]));
						
					}
					
					tempList.add(prof);
					
				}
			}
		searchRsList=this.dealProfitSummary(tempList);
		
		} catch (Exception e) {
			logger.error("数据处理异常"+e.getMessage(),e);
		}
	}


	public Map<String,BigDecimal> getProfitPercent(List<Object> list) throws ServiceException {
		Map<String,BigDecimal> map = new HashMap<String,BigDecimal>();
		BigDecimal transAmt = new BigDecimal(0);

		for (Object pro : list) {
			Object[] obj=(Object[]) pro;
			String accountNo ="";
			if(1==searchCondition.getTotalType()){
				accountNo =Constance.Null2EmptyTrim(obj[6]);
			}else if(2==searchCondition.getTotalType()){
				accountNo =Constance.Null2EmptyTrim(obj[6]);
			}else{
				accountNo =Constance.Null2EmptyTrim(obj[7]);
				
			}
			
			
			BigDecimal amt =new BigDecimal(Constance.null2Amt(obj[1]));
			
			if(map.containsKey(accountNo)){
				transAmt=map.get(accountNo);
				transAmt = transAmt.add(amt);
				map.put(accountNo, transAmt);
			}else{
				transAmt = amt;
				map.put(accountNo, transAmt);
			}
			
			
		}
		Map<String,BigDecimal> mapPercent = new HashMap<String,BigDecimal>();
		for(Map.Entry<String, BigDecimal> entry : map.entrySet())   
		{   
			String perStr = profitService.getProfitPercent(entry.getKey(), entry.getValue());
			mapPercent.put(entry.getKey(), new BigDecimal(perStr));
		} 
		return mapPercent;
	}
	
	
	/**
	 * 计算实际分润金额
	 * @throws ServiceException 
	 */
	public List<Object> dealProfitSummary(List<ProfitDetail> list) throws ServiceException {
		List<Object> restList= new ArrayList<Object>();
		Map<String,BigDecimal> map = new HashMap<String,BigDecimal>();
		BigDecimal transAmt = new BigDecimal(0);

		for (ProfitDetail pro : list) {
			if(map.containsKey(pro.getAccountNo())){
				transAmt=map.get(pro.getAccountNo());
				transAmt = transAmt.add(pro.getSAmt());
				map.put(pro.getAccountNo(), transAmt);
			}else{
				transAmt = transAmt.add(pro.getSAmt());
				map.put(pro.getAccountNo(), transAmt);
			}
		}
		Map<String,BigDecimal> mapPercent = new HashMap<String,BigDecimal>();
		for(Map.Entry<String, BigDecimal> entry : map.entrySet())   
		{   
			String perStr = profitService.getProfitPercent(entry.getKey(), entry.getValue());
			mapPercent.put(entry.getKey(), new BigDecimal(perStr));
		} 
		
		// 统计分润金额
		for (ProfitDetail pro : list) {
			BigDecimal profitAmt = pro.getMerfee();
			BigDecimal percent = mapPercent.get(pro.getAccountNo());
			pro.setPercent(percent);
			pro.setRealMerfee(profitAmt.multiply(percent));
			restList.add(pro);
		}

		return restList;
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_PROFIT_DASUM_QUERY);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_PROFIT_DASUM_QUERY, searchCondition);
	}


	public ProfitDASumQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(ProfitDASumQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public InputStream getExcelFile() {
		return excelFile;
	}


	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		return excelName;
	}


	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}


	
}
